import React, {useState, useEffect} from 'react'
import {useLocation} from 'react-router-dom'
import {useStore} from '../store'

export default function TodoForm(props) {
  const [txt, setTxt] = useState('')//修改文本
  const [id, setId] = useState('')//修改id
  const location = useLocation()//路径
  const store = useStore()

  useEffect(() => {
    const editId = location.search.split('=')[1]//截取携带的id
    console.log('TodoForm-match', editId)

    if(editId) {//存在id 展现id和信息 不存在的话就是新增
      const todo = store.todoStore.getTodo(editId)
      console.log(todo)

      setTxt(todo.body)
      setId(editId)
    }
    console.log('todoFrom',location)
    console.log('todoFrom.props',props)
  }, [])

  const changeTxt = (e) => {
    setTxt(e.target.value)
  }
  const submitHandler = () => {
    props.onClick({
      id,
      txt
    })
    setTxt('')
    setId('')
    
  }
  return (
    <div className='todo-form'>
      <input type="text" value={txt} onChange={changeTxt} />
      <button onClick={submitHandler}>提交</button>
    </div>
  )
}
